package com.yourannet.utils;

import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;

public class GpsUtils {
	
	/**
	 * 开启（关闭）GPS
	 * 如果当前未开启GPS，则开启，反之则关闭
	 * @param context
	 */
	public static void toggleGPS(Context context) {
	    	Intent gpsIntent = new Intent();
	        gpsIntent.setClassName("com.android.settings","com.android.settings.widget.SettingsAppWidgetProvider");
	        gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
	        gpsIntent.setData(Uri.parse("custom:3"));
	        try {
	        	PendingIntent.getBroadcast(context, 0, gpsIntent, 0).send();
	        }catch (CanceledException e) {
	        	e.printStackTrace();
	        }
    }
	 public static void openGPSSettings(Context context) {      
         //获取GPS现在的状态（打开或是关闭状态）
       boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled( context.getContentResolver(), LocationManager.GPS_PROVIDER );
       if(gpsEnabled)
       {

       //关闭GPS
        Settings.Secure.setLocationProviderEnabled( context.getContentResolver(), LocationManager.GPS_PROVIDER, false );
       }
       else
       {
        //打开GPS
        Settings.Secure.setLocationProviderEnabled( context.getContentResolver(), LocationManager.GPS_PROVIDER, true);
       }
    }
	/**
	 * 判断GPS是否可用，可用返回true，否则返回false
	 * @param context
	 * @return
	 */
	public static boolean isGPSEnable(Context context) {
        /* 用Setting.System来读取也可以，只是这是更旧的用法
        String str = Settings.System.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        */
        String str = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        Log.v("GPS", str);
        if (str != null) {
            return str.contains("gps");
        }
        else{
            return false;
        }
    }
}
